<template>
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    :immediate-check="false"
    @load="onLoad"
    :error.sync="error"
    error-text="加载失败,请稍后重试!"
  >
   <!-- :immediate-check="false" 关闭首次初始化检查 -->
    <!-- <van-cell
      v-for="(item, index) in list"
      :key="index"
      :title="item.content"
    /> -->
    <CommentItem
      v-for="(item, index) in list"
      :key="index"
      :comment="item"
      @reply-click="$emit('reply-click',$event)"
    ></CommentItem>
  </van-list>
</template>

<script>
import { getComments } from "@/api/comment.js";
import CommentItem from "./comment-item.vue";
export default {
  name: "CommentList",
  data() {
    return {
      // list: [],
      loading: false,
      finished: false,
      offset: null, //页码
      limit: 10,
      error: false,
    };
  },
  props: {
    source: {
      type: [Number, String, Object],
      required: true,
    },
    list:{
      type:Array,
      // 设置默认值;
      default:()=>[]
    },
    type:{
      type:String,
      // 自定义prop数据验证;
      validator(value){
        return ["a","c"].includes(value)
      },
      default:"a"
    }
  },
  methods: {
    async onLoad() {
      // 1. 请求数据
      // 2. 将数据添加到列表中
      // 3.将loading设置为false;
      // 4.判断是否还有数据
      // 有=>更新
      // 没有则 finish = true;
      //  子组件请求 把数据传给父组件 父组件接收请求;
       this.loading = true;
      try {
        const { data } = await getComments({
          type: this.type,
          source: this.source.toString(),
          offset: this.offset,
          limit: this.limit,
        });
        let { results } = data.data;
        // 把文章的总数量传递到外部
        this.$emit("onload-success", data.data);
        //  更新数据
        this.list.push(...results);
      // console.log(this.list);
        // 关闭加载状态;
       
        // 判断是否还有新数据
        if (results.length) {
          // 如果还有数据 则更新
          this.offset = data.data.last_id;
        } else {
          // 否则 不再更新 加载完毕;
          this.finished = true;
        }
      } catch (err) {
        console.log(err);
          console.log(this.list);
        this.error = true; //错误后不再加载;
       
        // console.log(err);
        // console.log("请求失败!");
      }
       this.loading = false;
    },
  },
  created() {
    this.loading = true;
    this.onLoad();
  },
  components: {
    CommentItem,
  },
};
</script>

<style scoped lang="less"></style>
